package com.jiudengnile.dr.myposition;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;

public class HttpUploader {
	
	private static final String uploadUrl = "http://u.jiudengnile.com/upload_data.htm";
	
	private static final String CHARSET = "utf-8";
	
	private static final int TIMEOUT = 5000;
	
	public String upload(String uid, List<String> data) throws IOException {
		URL url = new URL(uploadUrl);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(TIMEOUT);
		conn.setConnectTimeout(TIMEOUT);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		
		byte[] bdata = data2bytes(uid, data);
		
		conn.addRequestProperty("Content-Length", String.valueOf(bdata.length));
		
		OutputStream os = conn.getOutputStream();
		os.write(bdata);
		os.close();
		
		InputStream is = conn.getInputStream();
		String s = readString(is);
		is.close();
		return s;
	}
	
	static String readString(InputStream is) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		while (true) {
			int len = is.read(buf);
			if (len < 0) {
				break;
			}
			bos.write(buf, 0, len);
		}
		bos.close();
		return bos.toString(CHARSET);
	}

	static byte[] data2bytes(String uid, List<String> data) throws IOException  {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		String d = URLEncoder.encode(join(data, "\r\n"),CHARSET);
		String u = URLEncoder.encode(uid, CHARSET);
		bos.write(("uid=" + u).getBytes(CHARSET));
		bos.write(("&data=" + d).getBytes(CHARSET));
		bos.close();
		return bos.toByteArray();
	}
	
	static String join(Collection<String> c, String token) {
		StringBuilder sb = new StringBuilder();
		for (String d : c) {
			sb.append(d);
			sb.append(token);
		}
		return sb.toString();
	}
	
}
